package com.humanres.activity;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ciko.code.base.BaseActicity;
import com.ciko.code.bean.User;
import com.ciko.code.constant.Constants;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.Req.AddLeaveFlowReq;
import com.ciko.code.http.Req.GetAllLeaveTypesReq;
import com.ciko.code.http.Req.GetNextPersonReq;
import com.ciko.code.type.EmployeeEnum;
import com.ciko.code.utils.DateUtil;
import com.ciko.code.utils.MultiCard;
import com.ciko.code.utils.ScreenUtil;
import com.ciko.code.utils.Util;
import com.mywork.R;
import com.squareup.picasso.Picasso;
import com.ui.dialog.HeaderImageDialog;
import com.ui.pickerview.view.TimePickerView;
import com.ui.pickerview.view.TimePickerView.OnTimeSelectListener;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;


/**
 * Created by 12154 on 2015/11/1.
 */
public class ResLeaveActivity
        extends
        BaseActicity
        implements
        HeaderImageDialog.OnUserinfoMenuClickListener, OnTimeSelectListener {

    private RelativeLayout rectchooseType;
    private RelativeLayout rectchooseTimeStart;
    private RelativeLayout rectchooseTimeEnd;

    private TextView tv_endTimeLeave;
    private TextView tv_dayCountLeave;
    private TextView tv_Job;
    private TextView tv_Name;
    private TextView tv_startTimeLeave;
    private ImageView ivHanderIcon;
    private EditText etresonLeave;
    private Button btnsubmitLeave;


    private long startTime = 0;
    private long endTime = 0;
    private String startDate;
    private String endDate;
    private String startPart;//上午or下午
    private String endPart;//上午or下午

    private Spinner actv_type;
    private int dayCount = 0;
    private double count = 0;
    private String type;
    private String reson = "";
    private HeaderImageDialog imgSetDialog;
    public static File mImageFile;          //图片文件

    User nextUser = null;


    private TimePickerView pvTime;
    private boolean isStartTime = true;
    private SimpleDateFormat sdf = null;
    private SimpleDateFormat sdf2 = null;

    @Override
    protected void initTopBar() {
        setTitle("请假申请");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_res_leave);
    }

    @Override
    protected void initView() {
        actv_type = (Spinner) findViewById(R.id.actv_type);

        btnsubmitLeave = (Button) findViewById(R.id.btn_submitLeave);
        tv_startTimeLeave = (TextView) findViewById(R.id.tv_startTimeLeave);
        tv_endTimeLeave = (TextView) findViewById(R.id.tv_endTimeLeave);
        tv_dayCountLeave = (TextView) findViewById(R.id.tv_dayCountLeave);
        etresonLeave = (EditText) findViewById(R.id.et_resonLeave);
        rectchooseTimeEnd = (RelativeLayout) findViewById(R.id.rect_chooseTimeEnd);
        rectchooseTimeStart = (RelativeLayout) findViewById(R.id.rect_chooseTimeStart);
        rectchooseType = (RelativeLayout) findViewById(R.id.rect_chooseType);
        //        tv_Retroactive = (TextView) findViewById(R.id.tv_Retroactive);
        ivHanderIcon = (ImageView) findViewById(R.id.ivHanderIcon);
        tv_Job = (TextView) findViewById(R.id.tvJob);
        tv_Name = (TextView) findViewById(R.id.tvName);

//        imgSetDialog = new HeaderImageDialog(ResLeaveActivity.this, this);
//        findViewById(R.id.rlyt_update_img).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                imgSetDialog.show();
//            }
//        });

        pvTime = new TimePickerView(this, TimePickerView.Type.SHX);
        // 控制时间范围
        Calendar calendar = Calendar.getInstance();
        pvTime.setRange(calendar.get(Calendar.YEAR) - 10,
                calendar.get(Calendar.YEAR) + 25);
        pvTime.setTime(null);
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
        ScreenUtil.GetInfo(this);
        doRequestHttp(new GetAllLeaveTypesReq());

        doRequestHttp(new GetNextPersonReq());
    }

    @Override
    protected void initListener() {
        rectchooseType.setOnClickListener(this);
        rectchooseTimeStart.setOnClickListener(this);
        rectchooseTimeEnd.setOnClickListener(this);
        btnsubmitLeave.setOnClickListener(this);
        pvTime.setOnTimeSelectListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        if (v == btnsubmitLeave) {
            if (check()) {
                progressDialog.show();
                doRequestHttp(new AddLeaveFlowReq(type, 0, startTime, endTime, count, reson, "", nextUser.getId(), nextUser.getStaffName()));
            }
        } else if (v == rectchooseTimeEnd) {
            hideSoftInput();
            isStartTime = false;
            pvTime.setTime(null);
            pvTime.show();
        } else if (v == rectchooseTimeStart) {
            hideSoftInput();
            isStartTime = true;
            pvTime.setTime(null);
            pvTime.show();
        } else if (v == rectchooseType) {

        }
    }

    private boolean check() {

        type = actv_type.getSelectedItem().toString();

        reson = etresonLeave.getText().toString().trim();

        if (type.contains("请选择")) {
            showToast("请选择请假类型");
            return false;
        } else if (startTime == 0) {
            showToast("请选择开始时间");
            return false;
        } else if (endTime == 0) {
            showToast("请选择结束时间");
            return false;
        } else if (dayCount < 0) {
            showToast("结束时间必须大于开始时间");
            return false;
        } else if (TextUtils.isEmpty(reson)) {
            showToast("请填写请假事由");
            return false;
        } else if (reson.length() > 50) {
            showToast("字数不能超过50字");
            return false;
        } else if (null == nextUser) {
            showToast("请选择审批人");
            return false;
        }

        return true;
    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        super.onResponseSuccess(response, tag);

        switch (tag) {
            case "":
                break;
            case "AddLeaveFlowReq":
                progressDialog.dismiss();
                showToast("提交成功");
                Intent intent = new Intent();
                setResult(1001, intent);
                finish();
                break;
            case "GetNextPersonReq":
                nextUser = (User) response.getReturnObject();
                if (null != nextUser) {
                    tv_Job.setText(EmployeeEnum.typeOfValue(nextUser.getUserPositionMark()));
                    tv_Name.setText(nextUser.getStaffName());
                    if (!TextUtils.isEmpty(nextUser.getUserHead()))
                        Picasso.with(this).load(nextUser.getUserHead()).into(ivHanderIcon);
                    if (nextUser.getUserPositionMark() == 9999) {
                        Util.showToast(this, R.string.params_less_tip);
                    }
                }
                break;
        }
    }

    @Override
    public void openCamera() {
        if (Util.isSDCardSapceForWriteWithTip(ResLeaveActivity.this, MultiCard.TYPE_IMAGE, 0, true)) {
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String fileName = UUID.randomUUID().toString() + ".jpg";
        mImageFile = new File(Util.getWritePathIgnoreError(fileName));
        Uri capturedImgUri = Uri.fromFile(mImageFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImgUri);
        try {
            Intent wrapperIntent = Intent.createChooser(intent, null);
            startActivityForResult(wrapperIntent, Constants.CAPTURE_IMAGE);
        } catch (ActivityNotFoundException e) {
            Util.showToast(ResLeaveActivity.this, "您的手机没有摄像头");
        }

    }

    @Override
    public void openLocal() {
        if (Util.isSDCardSapceForWriteWithTip(ResLeaveActivity.this, MultiCard.TYPE_IMAGE, 0, true)) {
            return;
        }
        Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
        mIntent.setType("image/*");
        Intent wrapperIntent = Intent.createChooser(mIntent, null);
        startActivityForResult(wrapperIntent, Constants.GET_LOCAL_IMAGE);

    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
        super.onResponseFail(tag, resultCode);
        switch (tag) {
            case "AddLeaveFlowReq":
                progressDialog.dismiss();
                Util.showToast(this, "提交失败，请稍后再试");
                break;

        }
    }

    @Override
    public void onBackPressed() {
        if (pvTime.isShowing()) {
            pvTime.dismiss();
        } else {
            this.finish();
        }
    }

    private void getDayCount() {
        if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
            long start = DateUtil.StringToDate(startDate, 7).getTime();
            long end = DateUtil.StringToDate(endDate, 7).getTime();
            if (start > end) {
                dayCount = -1;
                tv_dayCountLeave.setText("");
                return;
            }
            count = (end - start) / (24 * 60 * 60 * 1000);
            if ("上午".equals(startPart)) count += 0.5;
            if ("下午".equals(endPart)) count += 0.5;
            tv_dayCountLeave.setText(count + "天");
            dayCount = (int) count;
        }
    }

    @Override
    public void onTimeSelect(String time) {
        //2016年11月16日 上午
        long startTempTime = 0;
        if (isStartTime) {
            try {
                startPart = time.substring(time.lastIndexOf(" ") + 1, time.length());
                String curDate = "";
                String curTempDate = time.substring(0, time.lastIndexOf(" "));
                if ("上午".equals(startPart)) {
                    startTempTime = sdf2.parse(curTempDate).getTime();
                    curTempDate = curTempDate + " " + "09:00";
                    if (endTime != 0 && endTime < startTempTime) {
                        Toast.makeText(ResLeaveActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        startDate = curTempDate.substring(0, time.lastIndexOf(" "));
                        curDate = startDate + " " + "09:00";
                        startTime = sdf.parse(curDate).getTime();
                    }
                } else {
                    startTempTime = sdf2.parse(curTempDate).getTime();
                    curTempDate = curTempDate + " " + "18:00";
                    if (endTime != 0 && endTime < startTempTime) {
                        Toast.makeText(ResLeaveActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        startDate = curTempDate.substring(0, time.lastIndexOf(" "));
                        curDate = startDate + " " + "18:00";
                        startTime = sdf.parse(curDate).getTime();
                    }
                }
                getDayCount();
                if (0 == endTime) {
                    tv_startTimeLeave.setText(time);
                    tv_startTimeLeave.setTextColor(Color.BLACK);
                } else {
                    if (endTime - startTime >= 0) {
                        tv_startTimeLeave.setText(time);
                        tv_startTimeLeave.setTextColor(Color.BLACK);
                    } else {
                        Toast.makeText(ResLeaveActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            endPart = time.substring(time.lastIndexOf(" ") + 1, time.length());
            endDate = time.substring(0, time.lastIndexOf(" "));
            String curDate;
            if ("上午".equals(endPart)) {
                curDate = endDate + " " + "09:00";
            } else {
                curDate = endDate + " " + "18:00";
            }
            try {
                endTime = sdf.parse(curDate).getTime();
                getDayCount();
                if (0 == startTime) {
                    tv_endTimeLeave.setText(time);
                    tv_endTimeLeave.setTextColor(Color.BLACK);
                } else {
                    if (endTime - startTime >= 0) {
                        tv_endTimeLeave.setText(time);
                        tv_endTimeLeave.setTextColor(Color.BLACK);
                    } else {
                        Toast.makeText(ResLeaveActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }
}
